package com.xtedu.examproject.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xtedu.examproject.entity.*;
import com.xtedu.examproject.service.*;
import com.xtedu.examproject.util.PageHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

@WebServlet("/classesmanage/*")
public class ClassesServlet extends HttpServlet {
    private ClassesService classesService;
    private SubjectService subjectService;
    private CourseService courseService;
    private TeacherService teacherService;
    private ClassRoomService classRoomService;
    private StudentService studentService;

    public void init() {
        classesService = new ClassesService();
        subjectService = new SubjectService();
        courseService = new CourseService();
        teacherService = new TeacherService();
        classRoomService = new ClassRoomService();
        studentService = new StudentService();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        if (pathInfo == null) {
            getAllClasses(req, resp);
            return;
        }
        if (pathInfo.equals("/classesinfo")) {
            getAllClasses(req, resp);
            return;
        }
        if (pathInfo.equals("/allSubjectInfo")) {
            getAllSubjectInfo(req, resp);
            return;
        }
        if (pathInfo.equals("/allCourseInfo")) {
            getAllCourseInfo(req, resp);
            return;
        }
        if (pathInfo.equals("/allTeacherInfo")) {
            getAllTeacherInfo(req, resp);
            return;
        }
        if (pathInfo.equals("/allClassRoomInfo")) {
            getAllClassRoomInfo(req, resp);
        }
        if(pathInfo.equals("/select")){
            getClassesByCondition(req, resp);
        }
        if(pathInfo.equals("/getCourseBySubjectId")){
            getCourseBySubjectId(req, resp);
        }
        if(pathInfo.equals("/getTeacherByCourseId")){
            getTeacherByCourseId(req, resp);
        }
        if(pathInfo.equals("/getClassRoomBySubjectId")){
            getClassRoomBySubjectId(req, resp);
        }
        if(pathInfo.equals("/allClassesInfo")){
            getAllClassesInfo(req, resp);
        }
        if(pathInfo.equals("/delete")){
            deleteClasses(req, resp);
        }
        if(pathInfo.equals("/classstudentlist")){
            getClassesStudent(req, resp);
        }
        if(pathInfo.equals("/getClassesById")){
            getClassesById(req, resp);
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        if(pathInfo!=null&&pathInfo.equals("/add")){
            addClasses(req, resp);
        }
        if(pathInfo!=null&&pathInfo.equals("/update")){
            updateClasses(req, resp);
        }
    }

    /**
     * 查询所有班级
     */
    public void getAllClasses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int pageIndex = req.getParameter("pageIndex") == null ? 1 : Integer.parseInt(req.getParameter("pageIndex"));
            int pageSize = req.getParameter("pageSize") == null ? 10 : Integer.parseInt(req.getParameter("pageSize"));
            PageHelper page = classesService.findAllClassesByPage(pageIndex, pageSize);
            page.setServletName("classesinfo");
            HttpSession session = req.getSession();
            session.setAttribute("page", page);
            req.getRequestDispatcher("/WEB-INF/views/classesManage.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 查询所有班级 返回 json
     */
    public void getAllClassesInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            List<Classes> classes;
            classes = classesService.findAllClasses();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(classes);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有专业 返回 json
     */
    public void getAllSubjectInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            List<Subject> subjects;
            subjects = subjectService.findAllSubject();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(subjects);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有课程 返回json
     */
    public void getAllCourseInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            List<Course> courses;
            courses = courseService.findAllCourse();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(courses);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有教师 返回json
     */
    public void getAllTeacherInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            List<Teacher> teachers;
            teachers = teacherService.findAllTeacher();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(teachers);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有教室 返回json
     */
    public void getAllClassRoomInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            List<ClassRoom> classRooms;
            classRooms = classRoomService.findAllClassRoom();
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(classRooms);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 条件查询
     */
    public void getClassesByCondition(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int pageIndex = req.getParameter("pageIndex") == null ? 1 : Integer.parseInt(req.getParameter("pageIndex"));
            int pageSize = req.getParameter("pageSize") == null ? 10 : Integer.parseInt(req.getParameter("pageSize"));
            int classId = req.getParameter("classId") == null ? 0 : Integer.parseInt(req.getParameter("classId"));
            String className = req.getParameter("className")==null?null:req.getParameter("className");
            int subjectId = req.getParameter("subjectId") == null ? 0 : Integer.parseInt(req.getParameter("subjectId"));
            int courseId = req.getParameter("courseId") == null ? 0 : Integer.parseInt(req.getParameter("courseId"));
            int teacherId = req.getParameter("teacherId") == null ? 0 : Integer.parseInt(req.getParameter("teacherId"));
            int roomId = req.getParameter("roomId") == null ? 0 : Integer.parseInt(req.getParameter("roomId"));
            PageHelper page = classesService.findClassesByConditionByPage(pageIndex, pageSize, classId, className, subjectId, courseId, teacherId, roomId);
            page.setServletName("classesmanage");
            HttpSession session = req.getSession();
            session.setAttribute("page", page);
            req.getRequestDispatcher("/WEB-INF/views/classesManage.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加班级
     */
    public void addClasses(HttpServletRequest req, HttpServletResponse resp) {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            Classes classes = new Classes();
            classes.setName(req.getParameter("className"));
            classes.setCreateDate(new Date(System.currentTimeMillis()));
            classes.setSubjectId(Integer.parseInt(req.getParameter("subjectId")));
            classes.setCourseId(Integer.parseInt(req.getParameter("courseId")));
            classes.setTeacherId(Integer.parseInt(req.getParameter("teacherId")));
            classes.setRoomId(Integer.parseInt(req.getParameter("roomId")));
            classes.setState(Boolean.parseBoolean(req.getParameter("state")));
            int result = classesService.insertClasses(classes);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(result);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据专业id查询课程
     */
    public void getCourseBySubjectId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try{
            int subjectId = req.getParameter("subjectId") == null ? 0 : Integer.parseInt(req.getParameter("subjectId"));
            List<Course> courses = courseService.findBySubjectId(subjectId);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(courses);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据课程id查询教师
     */
    public void getTeacherByCourseId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try{
            int courseId = req.getParameter("courseId") == null ? 0 : Integer.parseInt(req.getParameter("courseId"));
            List<Teacher> teachers = teacherService.findByCourseId(courseId);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(teachers);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据专业查询教室
     */
    public void getClassRoomBySubjectId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try{
            int subjectId = req.getParameter("subjectId") == null ? 0 : Integer.parseInt(req.getParameter("subjectId"));
            List<ClassRoom> classRooms = classRoomService.findBySubjectId(subjectId);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(classRooms);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改班级
     */
    public void updateClasses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try{
            Classes classes = new Classes();
            classes.setId(Integer.parseInt(req.getParameter("id")));
            classes.setName(req.getParameter("name"));
            classes.setSubjectId(Integer.parseInt(req.getParameter("subjectId")));
            classes.setCourseId(Integer.parseInt(req.getParameter("courseId")));
            classes.setTeacherId(Integer.parseInt(req.getParameter("teacherId")));
            classes.setRoomId(Integer.parseInt(req.getParameter("roomId")));
            classes.setState(Boolean.parseBoolean(req.getParameter("state")));
            int result = classesService.updateClasses(classes);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(result);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除班级
     */
    public void deleteClasses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try {
            int classesId = Integer.parseInt(req.getParameter("id"));
            Classes classes = new Classes();
            classes.setId(classesId);
            int result = classesService.deleteClasses(classes);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(result);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 班级学生列表
     */
    public void getClassesStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            int pageIndex = req.getParameter("pageIndex") == null ? 1 : Integer.parseInt(req.getParameter("pageIndex"));
            int pageSize = req.getParameter("pageSize") == null ? 10 : Integer.parseInt(req.getParameter("pageSize"));
            int classId = req.getParameter("classId") == null ? 0 : Integer.parseInt(req.getParameter("classId"));
//            if (classId == 0){
//                getAllClasses(req, resp);
//                return;
//            }
            PageHelper page = studentService.findClassesStudents( pageIndex, pageSize,classId);
            page.setServletName("classstudentlist");
            HttpSession session = req.getSession();
            session.setAttribute("page", page);
            req.getRequestDispatcher("/WEB-INF/views/classesStudent.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id查询班级
     */
    public void getClassesById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try{
            int classId = req.getParameter("classId") == null ? 0 : Integer.parseInt(req.getParameter("classId"));
            if(classId == 0){
                return;
            }
            Classes classes = classesService.findClassesById(classId);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(classes);
            resp.getWriter().write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
